import { Channel, HomeAction, Article } from "@/types/store"

type HomeType = {
  userChannels: Channel[],
  allChannels: Channel[]
  active: number,
  channelArticles: {
    [key: number]: {
      timestamp: string
      articles: Article[]
    }
  }
}

const initValue: HomeType = {
  userChannels: [],
  allChannels: [],
  active: 0, // 默认高亮的值
  channelArticles: {}, // 文章列表
}

export default function home(state = initValue, action: HomeAction) {

  switch (action.type) {
    case 'home/getUserChannel':
      return {
        ...state,
        userChannels: action.payload
      }
    case 'home/getAllChannels':
      return {
        ...state,
        allChannels: action.payload
      }
    case 'home/changeActive':
      return {
        ...state,
        active: action.payload
      }
    case 'home/saveChannelArticles':
      const { channel_id, timestamp, articles } = action.payload
      const oldArticles = state.channelArticles[channel_id]?.articles || []
      console.log(oldArticles, articles, timestamp);
      return {
        ...state,
        channelArticles: {
          ...state.channelArticles,
          [channel_id]: {
            timestamp,
            articles: [...oldArticles, ...articles],
          },
        },
      }
    case 'home/saveNewArticles':
      const { channel_id: id, timestamp: time, articles: article } = action.payload
      return {
        ...state,
        channelArticles: {
          // 需要追加数据
          ...state.channelArticles,
          [id]: {
            timestamp: time,
            articles: [...article],
          },
        },
      }
    default:
      return state
  }
}